package com.qian.ddj.pay.util;

import java.io.*;
import java.net.*;
import java.net.ProtocolException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import com.yaowk.api.common.BaseException;
import org.apache.commons.lang3.RandomUtils;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.RequestAcceptEncoding;
import org.apache.http.client.protocol.ResponseContentEncoding;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.*;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;
public class HttpRequestUtil {
    private static final String GET = "GET";
    private static final String POST = "POST";
    private static String CHARSET = "UTF-8";
    private static final String[] USER_AGENTS = new String[] {
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.102 Safari/537.36",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1309.0 Safari/537.17",
            "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko",
            "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.94 Safari/537.36 OPR/24.0.1558.53" };

    private static final CloseableHttpClient HTTP_CLIENT;
    private static final RequestConfig DEFAULT_REQUEST_CONFIG;
    static {
        HttpClientBuilder httpClientBuilder = HttpClients.custom();

        DEFAULT_REQUEST_CONFIG = RequestConfig.custom().setExpectContinueEnabled(false) // 设置不使用Expect:100-Continue握手
                .setConnectTimeout(10000) // 设置连接超时时间
                .setSocketTimeout(60000 * 3) // 设置读数据超时时间
                .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY) // Cookie策略
                .build();
        httpClientBuilder.setDefaultRequestConfig(DEFAULT_REQUEST_CONFIG);

        httpClientBuilder.addInterceptorFirst(new RequestAcceptEncoding()); // 设置GZIP请求的支持
        httpClientBuilder.addInterceptorFirst(new ResponseContentEncoding()); // 设置GZIP响应的支持
        httpClientBuilder.setUserAgent(getRandomUserAgent()); // 设置User-Agent

        HttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(1, true);
        httpClientBuilder.setRetryHandler(retryHandler); // 设置重试

        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", SSLConnectionSocketFactory.getSocketFactory()).build();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
        connectionManager.setMaxTotal(400);
        connectionManager.setDefaultMaxPerRoute(200);

        SocketConfig defaultSocketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
        connectionManager.setDefaultSocketConfig(defaultSocketConfig);

        // Create connection configuration
        ConnectionConfig defaultConnectionConfig = ConnectionConfig.custom().setCharset(Consts.UTF_8).build();
        connectionManager.setDefaultConnectionConfig(defaultConnectionConfig);

        httpClientBuilder.setConnectionManager(connectionManager);
        httpClientBuilder.setRedirectStrategy(DefaultRedirectStrategy.INSTANCE);
        HTTP_CLIENT = httpClientBuilder.build();
    }
    public static String getRandomUserAgent() {
        return USER_AGENTS[RandomUtils.nextInt(0, USER_AGENTS.length)];
    }
    public static String execute(HttpUriRequest request) throws ClientProtocolException, IOException {
        return HTTP_CLIENT.execute(request, new BasicResponseHandler());
    }
    /*
     * POST /webservice.asmx/mdsmssend HTTP/1.1 Host: sdk.entinfo.cn
     * Content-Type: application/x-www-form-urlencoded Content-Length: length
     *
     * sn=string&pwd=string&mobile=string&content=string&ext=string&stime=string
     * &rrid=string&msgfmt=string
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            URL realUrl = new URL(url);
            // ���β������ε�SSL��������
            // SslUtil.ignoreSsl();
            // ����ͨ�ô���
            // System.setProperty("http.proxyHost",
            // "myProxyServer.com");System.setProperty("http.proxyPort", "80");
            // �򿪺�URL֮�������
            URLConnection conn = realUrl.openConnection();
            // ����ͨ�õ���������
            conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            // ����POST��������
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // Post ������ʹ�û���
            conn.setUseCaches(false);
            // �������ӳ�ʱ
            conn.setConnectTimeout(600000);
            // ���ö�ȡ��ʱ
            conn.setReadTimeout(600000);
            // ��ȡURLConnection�����Ӧ�������
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
            // �����������
            out.print(param);
            // flush������Ļ���
            out.flush();
            // ����BufferedReader����������ȡURL����Ӧ
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            // System.out.println(result.toString());
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("���� POST ��������쳣��");
            result.append("{\"respCode\":\"01\",\"message\":\"���Žӿ�ͨѶ�쳣��\"}");
        }
        // ʹ��finally�����ر��������������
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        System.out.println("***********************" + result);
        return result.toString();
    }

    /**
     * ���ɲ���
     *
     * @param params
     * @return
     */
    public static StringBuilder buildParam(Map<String, Object> params) {
        StringBuilder strParam = new StringBuilder();
        for (String key : params.keySet()) {
            strParam.append(key).append("=").append(params.get(key)).append("&");
        }
        return strParam;
    }

    /**
     * ��ȡ����request�������key-value
     *
     * @param request
     * @return
     */
    public static Map<String, String> getRequestParams(HttpServletRequest request) {

        Map<String, String> params = new HashMap<String, String>();
        if (null != request) {
            Set<String> paramsKey = request.getParameterMap().keySet();
            for (String key : paramsKey) {
                params.put(key, request.getParameter(key));
            }
        }
        return params;
    }

    public static String httpPostSendReceive(String url, String jsonString) throws IOException {
        return httpPostSendReceiveWithType(url, jsonString, "text/plain;charset=UTF-8");
    }

    public static String httpPostSendReceiveJson(String url, String jsonString) throws IOException {
        return httpPostSendReceiveWithType(url, jsonString, "application/json;charset=UTF-8");
    }

    public static String httpPostSendReceiveWithType(String url, String jsonString, String contentType)
            throws IOException {

        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        String res = null;

        try {
            System.out.println("����url��" + url);
            HttpPost httpPost = new HttpPost(url);
            StringEntity entityParams = new StringEntity(jsonString, "UTF-8");
            System.out.println("��������" + new String(EntityUtils.toByteArray(entityParams), "UTF-8"));
            httpPost.setEntity(entityParams);
            httpPost.setHeader("Content-Type", contentType);
            httpPost.setHeader("dataType", "json");
            client = HttpClients.createDefault();
            response = client.execute(httpPost);
            HttpEntity httpEntity = response.getEntity();

            if (response == null || httpEntity == null) {
                res = "����ʧ��";
                return "";
            }
            res = new String(EntityUtils.toByteArray(httpEntity), "UTF-8");
            System.out.println("��������" + res);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return "";
        } finally {
            if (response != null) {
                response.close();
            }
            if (client != null) {
                client.close();
            }
        }
        return res;
    }

    /**
     * httpPost
     *
     * @param url       ·��
     * @param jsonParam ����
     * @return
     */
    public static JSONObject httpPost(String url, JSONObject jsonParam) {
        return httpPost(url, jsonParam, false);
    }

    public static JSONObject httpPost(String url, String jsonParam) {
        return httpPost(url, JSONObject.parseObject(jsonParam), false);
    }

    public static String httpPost(String url, List<NameValuePair> nvps) {
        // post���󷵻ؽ��

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // JSONObject jsonResult = null;
        HttpPost method = new HttpPost(url);
        try {
            method.setEntity(new UrlEncodedFormEntity(nvps));
            HttpResponse result = httpClient.execute(method);
            url = URLDecoder.decode(url, "UTF-8");
            /** �����ͳɹ������õ���Ӧ **/
            if (result.getStatusLine().getStatusCode() == 200) {
                try {
                    /** ��ȡ���������ع�����json�ַ������� **/
                    return EntityUtils.toString(result.getEntity());
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("post�����ύʧ��:" + url);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("post�����ύʧ��:" + url);
        }
        return "";
    }

    /**
     * post����
     *
     * @param url            url��ַ
     * @param jsonParam      ����
     * @param noNeedResponse ����Ҫ���ؽ��
     * @return
     */
    public static JSONObject httpPost(String url, JSONObject jsonParam, boolean noNeedResponse) {
        // post���󷵻ؽ��

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        JSONObject jsonResult = null;
        HttpPost method = new HttpPost(url);
        try {
            if (null != jsonParam) {
                // ���������������
                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                method.setEntity(entity);
            }
            HttpResponse result = httpClient.execute(method);
            url = URLDecoder.decode(url, "UTF-8");
            /** �����ͳɹ������õ���Ӧ **/
            if (result.getStatusLine().getStatusCode() == 200) {
                String str = "";
                try {
                    /** ��ȡ���������ع�����json�ַ������� **/
                    str = EntityUtils.toString(result.getEntity());
                    if (noNeedResponse) {
                        return null;
                    }
                    /** ��json�ַ���ת����json���� **/
                    jsonResult = JSONObject.parseObject(str);
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("post�����ύʧ��:" + url);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("post�����ύʧ��:" + url);
        }
        return jsonResult;
    }

    /**
     * ����get����
     *
     * @param url �����ַ
     * @return
     */
    public static JSONObject httpGetJson(String url) {
        // get���󷵻ؽ��
        JSONObject jsonResult = null;
        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        try {
            client = HttpClientBuilder.create().build();
            // ����get����
            HttpGet request = new HttpGet(url);
            response = client.execute(request);

            /** �����ͳɹ������õ���Ӧ **/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /** ��ȡ���������ع�����json�ַ������� **/
                String strResult = EntityUtils.toString(response.getEntity());
                /** ��json�ַ���ת����json���� **/
                jsonResult = JSONObject.parseObject(strResult);
                url = URLDecoder.decode(url, "UTF-8");
            } else {
                System.out.println("get�����ύʧ��:" + url);
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("get�����ύʧ��:" + url);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                }
            }
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                }
            }
        }
        return jsonResult;
    }

    /**
     * ����һ���ֽ���
     *
     * @param url
     * @return
     * @throws IOException
     */
    public static ByteArrayInputStream httpGetSream(String url, String charset) {
        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        String res = null;

        try {
            System.out.println("����url��" + url);
            HttpGet httpGet = new HttpGet(url);

            httpGet.setHeader("Content-Type", "text/plain;charset=" + charset);
            client = HttpClients.createDefault();
            response = client.execute(httpGet);
            HttpEntity httpEntity = response.getEntity();

            if (response == null || httpEntity == null) {
                res = "����ʧ��";
                System.out.println(res + ": response == null || httpEntity == null");
                return null;
            }
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                res = "����ʧ��" + statusCode;
                System.out.println(res + ": response.getStatusLine().getStatusCode() = " + statusCode);
                return null;
            }

            return new ByteArrayInputStream(EntityUtils.toByteArray(httpEntity));
        } catch (Exception e) {
            System.out.println("��������");
            e.printStackTrace();
            return null;
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                }
            }
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                }
            }
        }
    }

    public static String httpGetStr(String url) {
        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        String res = null;

        try {
            System.out.println("����url��" + url);
            HttpGet httpGet = new HttpGet(url);

            httpGet.setHeader("Content-Type", "text/plain;charset=UTF-8");
            client = HttpClients.createDefault();
            response = client.execute(httpGet);
            HttpEntity httpEntity = response.getEntity();

            if (response == null || httpEntity == null) {
                res = "����ʧ��";
                System.out.println(res + ": response == null || httpEntity == null");
                return "";
            }
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                res = "����ʧ��" + statusCode;
                System.out.println(res + ": response.getStatusLine().getStatusCode() = " + statusCode);
                return "";
            }

            res = new String(EntityUtils.toByteArray(httpEntity), "UTF-8");
            System.out.println("��������" + res);
        } catch (Exception e) {
            System.out.println("��������");
            e.printStackTrace();
            return "";
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                }
            }
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                }
            }
        }
        return res;

    }


    public static String jsonPost(String strURL, String data) {
        try {
            URL url = new URL(strURL);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.connect();
            OutputStream out = connection.getOutputStream(); // utf-8编码
            out.write(data.getBytes("UTF-8"));
            out.flush();
            out.close();
            String result = readResponseString(connection); // utf-8编码
            return result;


        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (ProtocolException e1) {
            e1.printStackTrace();
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    return null;
    }



    private static String readResponseString(HttpURLConnection conn) {
        BufferedReader reader = null;

        String var4;
        try {
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), CHARSET));
            String line = reader.readLine();
            if (line != null) {
                StringBuilder ret = new StringBuilder();
                ret.append(line);

                while ((line = reader.readLine()) != null) {
                    ret.append('\n').append(line);
                }

                var4 = ret.toString();
                return var4;
            }

            var4 = "";
        } catch (Exception var14) {
            throw new RuntimeException(var14);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException var13) {

                }
            }

        }

        return var4;
    }
}